package com.boarsoft.boar.office.meeting.action;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boarsoft.bean.LogonI;
import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.common.Constants;
import com.boarsoft.boar.office.entity.MeetingInfo;
import com.boarsoft.boar.office.entity.MeetingUser;
import com.boarsoft.boar.office.entity.OfficeGroupUser;
import com.boarsoft.boar.office.group.OfficeGroupUserBiz;
import com.boarsoft.boar.office.meeting.MeetingBiz;
import com.boarsoft.boar.office.meeting.MeetingUserBiz;
import com.boarsoft.common.Authorized;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.flow.core.SimpleFlow;
import com.boarsoft.flow.core.SimpleFlowEngine;
import com.boarsoft.web.controller.BaseController;
import com.boarsoft.web.login.Logined;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@RestController
@RequestMapping("/meeting")
public class MeetingAction extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(MeetingAction.class);

	@Autowired
	private MeetingBiz meetingBiz;
	@Autowired
	private MeetingUserBiz meetingUserBiz;
	@Autowired
	private OfficeGroupUserBiz groupUserBiz;

	@Autowired
	private SimpleFlowEngine flowEngine;

	@JsonIgnoreProperties(value = { "roles" })
	@RequestMapping("/index.do")
	@Authorized(code = "office.meeting.index")
	public ReplyInfo<Object> index(@Logined LogonI<String> logon, String groupId, String key, String orderBy, int pageNo,
			int pageSize) {
		if (Util.strIsEmpty(groupId)) {
			// 如果没传groupId则取当前用户默认的Group
			OfficeGroupUser g = groupUserBiz.getUserDefaultGroupId(logon.getId());
			if (g != null) {
				groupId = g.getGroupId();
			}
		}
		PagedResult<MeetingInfo> pr = meetingBiz.list(//
				groupId, logon.getId(), key, orderBy, pageNo, pageSize);
		for (MeetingInfo o : pr.getList()) {
			o.setOwner(this.getSysUser(o.getOwnerId()));
		}
		return new ReplyInfo<Object>(true, pr);
	}

	/**
	 * 激活任务：创建并启动工作流
	 * 
	 * @param o
	 * @return
	 */
	@Authorized(code = "office.meeting.submit")
	@RequestMapping("/submit.do")
	public ReplyInfo<Object> submit(MeetingInfo o, String userIds) {
		if (Util.strIsEmpty(userIds)) {
			return Constants.REPLY_WARN_INVALID;
		}
		String[] ua = userIds.split(",");
		// TODO 通知所有与会人

		// 更新会议状态
		o.setStatus(MeetingInfo.STATUS_SCHEDULED);
		meetingBiz.update(o, ua);
		// 续跑关联的任务
		String flowId = o.getFlowId();
		if (Util.strIsEmpty(flowId)) {
			return ReplyInfo.SUCCESS;
		}
		String flowExeId = o.getFlowExeId();
		if (Util.strIsEmpty(flowExeId)) {
			return Constants.REPLY_WARN_INVALID;
		}
		try {
			SimpleFlow fo = flowEngine.resume(flowId, flowExeId, o);
			return new ReplyInfo<Object>(true, fo.getData());
		} catch (Throwable e) {
			log.error("Error on resume flow {}/{}", flowId, flowExeId, e);
			return Constants.REPLY_ERROR_INTERNAL;
		}
	}

	@RequestMapping("/get.do")
	@Authorized(code = "office.meeting.get")
	public ReplyInfo<Object> get(String id) {
		MeetingInfo o = meetingBiz.get(id);
		o.setOwner(this.getSysUser(o.getOwnerId()));
		List<MeetingUser> muLt = meetingUserBiz.list(id, null);
		for (MeetingUser mu : muLt) {
			o.getUsers().add(this.getSysUser(mu.getUserId()));
		}
		return new ReplyInfo<Object>(true, o);
	}

	@RequestMapping("/save.do")
	@Authorized(code = "office.meeting.save")
	public ReplyInfo<Object> save(@Validated MeetingInfo o, String userIds) {
		if (Util.strIsEmpty(userIds)) {
			return Constants.REPLY_WARN_INVALID;
		}
		String[] ua = userIds.split(",");
		if (Util.strIsEmpty(o.getId())) {
			meetingBiz.save(o, ua);
		} else {
			meetingBiz.update(o, ua);
		}
		return ReplyInfo.SUCCESS;
	}

	@RequestMapping("/complete.do")
	@Authorized(code = "office.meeting.complete")
	public ReplyInfo<Object> complete(@Validated MeetingInfo o, String userIds) {
		String flowId = o.getFlowId();
		o.setStatus(MeetingInfo.STATUS_DONE);
		// 续跑关联的任务
		if (Util.strIsEmpty(flowId)) {
			return ReplyInfo.SUCCESS;
		}
		String flowExeId = o.getFlowExeId();
		if (Util.strIsEmpty(flowExeId)) {
			return Constants.REPLY_WARN_INVALID;
		}
		// 更新会议状态
		meetingBiz.update(o);
		try {
			SimpleFlow fo = flowEngine.resume(flowId, flowExeId, o);
			return new ReplyInfo<Object>(true, fo.getData());
		} catch (Throwable e) {
			log.error("Error on resume flow {}/{}", flowId, flowExeId, e);
			return Constants.REPLY_ERROR_INTERNAL;
		}
	}

	@RequestMapping("/cancel.do")
	@Authorized(code = "office.meeting.cancel")
	public ReplyInfo<Object> cancel(String id) {
		MeetingInfo o = meetingBiz.get(id);
		if (o.getStatus() == MeetingInfo.STATUS_DRAFT//
				|| o.getStatus() == MeetingInfo.STATUS_SCHEDULED) {
			o.setLastTime(Util.getStdfDate());
			o.setStatus(MeetingInfo.STATUS_CANCEL);
			meetingBiz.update(o);
			return ReplyInfo.SUCCESS;
		}
		return Constants.REPLY_WARN_INVALID;
	}

	@RequestMapping("/finish.do")
	@Authorized(code = "office.meeting.finish")
	public ReplyInfo<Object> finish(String id, short result) {
		MeetingInfo o = meetingBiz.get(id);
		if (o.getStatus() != MeetingInfo.STATUS_SCHEDULED) {
			return Constants.REPLY_WARN_INVALID;
		}
		o.setLastTime(Util.getStdfDate());
		o.setStatus(MeetingInfo.STATUS_DONE);
		o.setResult(result);
		meetingBiz.update(o);
		// 根据会议结论续跑关联的流程
		String flowId = o.getFlowId();
		if (Util.strIsEmpty(flowId)) {
			return ReplyInfo.SUCCESS;
		}
		String flowExeId = o.getFlowExeId();
		if (Util.strIsEmpty(flowExeId)) {
			return Constants.REPLY_WARN_INVALID;
		}
		try {
			SimpleFlow fo = flowEngine.resume(flowId, flowExeId, o);
			return new ReplyInfo<Object>(true, fo.getData());
		} catch (Throwable e) {
			log.error("Error on resume flow {}/{}", flowId, flowExeId, e);
			return Constants.REPLY_ERROR_INTERNAL;
		}
	}

	@RequestMapping("/close.do")
	@Authorized(code = "office.meeting.close")
	public ReplyInfo<Object> close(String id) {
		MeetingInfo o = meetingBiz.get(id);
		if (o.getStatus() == MeetingInfo.STATUS_DONE//
				|| o.getStatus() == MeetingInfo.STATUS_CANCEL) {
			o.setLastTime(Util.getStdfDate());
			o.setStatus(MeetingInfo.STATUS_CLOSED);
			meetingBiz.update(o);
			return ReplyInfo.SUCCESS;
		}
		return Constants.REPLY_WARN_INVALID;
	}

	/**
	 * 供首页使用的查询
	 * 
	 * @return
	 */
	// @JsonIgnoreProperties(value = { "" })
	@RequestMapping("/list.do")
	@Authorized(code = "office.meeting.list")
	public ReplyInfo<Object> list(@Logined LogonI<String> logon, String groupId, String key, //
			String ownerId, Short status, String orderBy, int pageNo, int pageSize) {
		if (Util.strIsEmpty(groupId)) {
			// 如果没传groupId则取当前用户默认的Group
			OfficeGroupUser g = groupUserBiz.getUserDefaultGroupId(logon.getId());
			if (g != null) {
				groupId = g.getGroupId();
			}
		}
		PagedResult<MeetingInfo> pr = meetingBiz.list(//
				groupId, ownerId, key, status, orderBy, pageNo, pageSize);
		for (MeetingInfo o : pr.getList()) {
			o.setOwner(this.getSysUser(o.getOwnerId()));
			// 查询此任务的明细日志
			// o.setLogs(officeWorkLogBiz.list(o.getId()));
		}
		return new ReplyInfo<Object>(true, pr);
	}
}